package com.example.springbootdemo.text;

//import org.apache.commons.math3.ml.distance.CosineDistance;

import java.util.HashMap;
import java.util.Map;

/**
 *  使用余弦相似性
 * 对于处理文档或句子时，可以使用词频-逆文档频率(TF-IDF)向量来计算余弦相似性。这里我们简化版本，直接基于词频。
 */
public class CosineSimilarity1 {
    public static double compute(String s1, String s2) {
        Map<String, Integer> tf1 = toTermFrequency(s1);
        Map<String, Integer> tf2 = toTermFrequency(s2);

        double dotProduct = 0.0;
        double normA = 0.0;
        double normB = 0.0;

        for (String term : tf1.keySet()) {
            if (tf2.containsKey(term)) {
                dotProduct += tf1.get(term) * tf2.get(term);
            }
            normA += Math.pow(tf1.get(term), 2);
        }
        for (Integer freq : tf2.values()) {
            normB += Math.pow(freq, 2);
        }

        return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
    }

    private static Map<String, Integer> toTermFrequency(String s) {
        Map<String, Integer> map = new HashMap<>();
        for (String word : s.split("\\s+")) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }
        return map;
    }

    public static void main(String[] args) {
        System.out.println(compute("the quick brown fox", "the lazy dog jumps over the quick brown fox"));
    }
}